package agentV1

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"hc_server/pkg/app"
	"hc_server/pkg/channel"
	"hc_server/pkg/file"
	"hc_server/pkg/setting"
	"hc_server/routers/api"
	"hc_server/routers/service/merchantService"
	"hc_server/runtime/e"
	"time"
)

type MerchantTempInfoAddParam struct {
	MerchantMobile     string      `json:"merchantMobile" binding:"required"` //商户手机号
	MerchantType       interface{} `json:"merchantType"`                      //商户类型 1=小微商户 2=个体商户 3=企业商户
	MerchantShopTypeId interface{} `json:"merchantShopTypeId"`                //店铺类型 1=主店 2=独立结算分店 3=合并结算分店 4=分账接收方
	AgentId            interface{} `json:"agentId"`                           //代理商id
	SalesmenId         interface{} `json:"salesmenId"`                        //业务员id
	MerchantId         interface{} `json:"merchantId,omitempty"`              //主店id 当店铺类型为2、3时必填
}

// MerchantTempInfoAdd 添加商户基础信息
func MerchantTempInfoAdd(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantTempInfoAddParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userId, _ := c.Get("userId")

	if len(cast.ToString(param.AgentId)) == 0 || cast.ToInt(param.AgentId) == 0 {
		param.AgentId = 1
	}

	merchantService := &merchantService.Merchant{
		UserId:             cast.ToInt(userId),
		MerchantMobile:     param.MerchantMobile,
		MerchantType:       cast.ToInt(param.MerchantType),
		MerchantShopTypeId: cast.ToInt(param.MerchantShopTypeId),
		AgentId:            cast.ToInt(param.AgentId),
		SalesmenId:         cast.ToInt(param.SalesmenId),
		MerchantId:         cast.ToInt(param.MerchantId),
	}

	result, err := merchantService.MerchantTempInfoAdd()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}
	appG.ResponseSuccess("添加成功", result)
}

type MerchantTempShopAddForm struct {
	Id                string `form:"id"`
	MerchantRangeCode string `form:"merchantRangeCode"` //经营范围code
	MerchantName      string `form:"merchantName"`      //商户名称
	MerchantLongitude string `form:"merchantLongitude"` //经度
	MerchantLatitude  string `form:"merchantLatitude"`  //纬度
	MerchantAddress   string `form:"merchantAddress"`   //详细地址
	MerchantAddressId string `form:"merchantAddressId"` //最后一级地区编码主键id
}

// MerchantTempShopAdd 添加商户门店信息
func MerchantTempShopAdd(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    MerchantTempShopAddForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	if len(form.Id) == 0 {
		appG.ResponseError("缺少参数id", nil)
		return
	}

	doorPic, err := api.VerifyFileAndSave(c, "doorPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}
	cashierPic, err := api.VerifyFileAndSave(c, "cashierPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}
	shopPic, err := api.VerifyFileAndSave(c, "shopPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	var fileList []*channel.LianImgUploadParam
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, doorPic), Remarks: "doorPic"})
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, cashierPic), Remarks: "cashierPic"})
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, shopPic), Remarks: "shopPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "doorPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-3776cc7979af7a68fadb22958fb65ba3_720w.jpg", Remarks: "cashierPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-3776cc7979af7a68fadb22958fb65ba3_720w.jpg", Remarks: "shopPic"})
	//总-门店关系说明函 merchant_shop_types = 3时必填
	relationCertPic, err := api.VerifyFileAndSave(c, "relationCertPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err == nil {
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchant/"+form.Id, relationCertPic), Remarks: "relationCertPic"})
	}
	err = channel.LianImgUpload(fileList, form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	merchantService := &merchantService.Merchant{
		Id:                        cast.ToInt(form.Id),
		MerchantRangeCode:         cast.ToInt(form.MerchantRangeCode),
		MerchantName:              form.MerchantName,
		MerchantLongitude:         cast.ToFloat64(form.MerchantLongitude),
		MerchantLatitude:          cast.ToFloat64(form.MerchantLatitude),
		MerchantAddress:           form.MerchantAddress,
		MerchantAddressId:         cast.ToInt(form.MerchantAddressId),
		MerchantFrontPhoto:        doorPic,
		MerchantCheckstandPhoto:   cashierPic,
		MerchantIndoorPhoto:       shopPic,
		MerchantRelationCertPhoto: relationCertPic,
	}

	err = merchantService.MerchantTempShopAdd()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("添加成功", map[string]string{"id": form.Id})
}

type MerchantTempLegalAddForm struct {
	Id                             string `form:"id"`
	LegalPersonName                string `form:"legalPersonName"`                //法人姓名
	LegalPersonIdcard              string `form:"legalPersonIdcard"`              //法人身份证
	LegalPersonIdcardValidityBegin string `form:"legalPersonIdcardValidityBegin"` //法人身份证有效期始 yyyy-MM-dd
	LegalPersonIdcardValidityEnd   string `form:"legalPersonIdcardValidityEnd"`   //法人身份证有效期至 yyyy-MM-dd，永久有效：上传“长期”
	LegalContactType               string `form:"legalContactType"`               //商户联系人类型 0-法人；1-委托人 ，小微，只能是0-法人
	LegalContactName               string `form:"legalContactName"`               //联系人姓名
	LegalContactIdCardNo           string `form:"legalContactIdCardNo"`           //联系人身份证号
	LegalContactMobile             string `form:"legalContactMobile"`             //联系人手机号
}

// MerchantTempLegalAdd 添加商户法人信息
func MerchantTempLegalAdd(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    MerchantTempLegalAddForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	if len(form.Id) == 0 {
		appG.ResponseError("缺少参数id", nil)
		return
	}

	idcardFrontPic, err := api.VerifyFileAndSave(c, "idcardFrontPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}
	idcardBackPic, err := api.VerifyFileAndSave(c, "idcardBackPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}
	idcardHoldPic, err := api.VerifyFileAndSave(c, "idcardHoldPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	var fileList = make([]*channel.LianImgUploadParam, 0)
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, idcardFrontPic), Remarks: "idcardFrontPic"})
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, idcardBackPic), Remarks: "idcardBackPic"})
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, idcardHoldPic), Remarks: "idcardHoldPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "idcardFrontPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "idcardBackPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "idcardHoldPic"})
	err = channel.LianImgUpload(fileList, cast.ToString(form.Id))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	// 定义布局字符串，该字符串需要匹配dateTimeStr的格式
	layout := "2006-01-02"

	// 解析字符串为time.Time对象
	_, err = time.Parse(layout, form.LegalPersonIdcardValidityBegin)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	_, err = time.Parse(layout, form.LegalPersonIdcardValidityEnd)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	merchantService := &merchantService.Merchant{
		Id:                             cast.ToInt(form.Id),
		LegalPersonName:                form.LegalPersonName,
		LegalPersonIdcard:              form.LegalPersonIdcard,
		LegalPersonIdcardValidityBegin: form.LegalPersonIdcardValidityBegin,
		LegalPersonIdcardValidityEnd:   form.LegalPersonIdcardValidityEnd,
		LegalPersonIdcardPhotoFront:    idcardFrontPic,
		LegalPersonIdcardPhotoBack:     idcardBackPic,
		LegalPersonIdcardHold:          idcardHoldPic,
		LegalContactType:               cast.ToInt(form.LegalContactType),
		LegalContactName:               form.LegalContactName,
		LegalContactIdCardNo:           form.LegalContactIdCardNo,
		LegalContactMobile:             form.LegalContactMobile,
	}

	err = merchantService.MerchantTempLegalAdd()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("添加成功", map[string]string{"id": form.Id})
}

type MerchantTempMerchantLicenseInfoAddParam struct {
	Id               string `form:"id"`
	LicenseName      string `form:"licenseName"`      //营业执照名称
	LicenseCode      string `form:"licenseCode"`      //执照注册号
	LicenseBeginTime string `form:"licenseBeginTime"` //执照注册开始时间
	LicenseEndTime   string `form:"licenseEndTime"`   //执照注册结束时间
	LicenseAddress   string `form:"licenseAddress"`   //执照地址
	ActivityId       string `form:"activityId"`       //活动id
}

// MerchantTempMerchantLicenseInfoAdd 添加商户营业执照信息
func MerchantTempMerchantLicenseInfoAdd(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    MerchantTempMerchantLicenseInfoAddParam
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	// 定义布局字符串，该字符串需要匹配dateTimeStr的格式
	layout := "2006-01-02"

	// 解析字符串为time.Time对象
	_, err := time.Parse(layout, form.LicenseBeginTime)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	// 解析字符串为time.Time对象
	_, err = time.Parse(layout, form.LicenseEndTime)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	licensePic, err := api.VerifyFileAndSave(c, "licensePic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+cast.ToString(form.Id))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	var fileList = make([]*channel.LianImgUploadParam, 0)
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+cast.ToString(form.Id), licensePic), Remarks: "licensePic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "licensePic"})
	err = channel.LianImgUpload(fileList, cast.ToString(form.Id))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	var activityId int
	activityId = cast.ToInt(form.ActivityId)
	merchantService := &merchantService.Merchant{
		Id:               cast.ToInt(form.Id),
		LicensePhoto:     licensePic,
		LicenseName:      form.LicenseName,
		LicenseCode:      form.LicenseCode,
		LicenseBeginTime: form.LicenseBeginTime,
		LicenseEndTime:   form.LicenseEndTime,
		LicenseAddress:   form.LicenseAddress,
		ActivityId:       &activityId,
	}

	err = merchantService.MerchantTempMerchantLicenseInfoAdd()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("添加成功", nil)
}

type MerchantTempBankAddForm struct {
	Id                    string `form:"id"`
	SettleAccountType     string `form:"accountType"`           //结算账户类型：1-法人对私；2-非法人对私；3-法人对公；merchantType=1-小微，该参数必须为1-法人对私
	SettleName            string `form:"settleName"`            //结算户名法人对私结算：与法人姓名一致；非法人对私结算：与非法人身份证信息一致；法人对公结算：与营业执照注册名称一致(非法人对私结算需要传值)
	SettleBankcardNo      string `form:"settleBankcardNo"`      //结算卡号
	SettleBankMobile      string `form:"settleBankMobile"`      //银行预留手机号
	SettleSubbranchCode   string `form:"settleSubbranchCode"`   //开户支行联行号 (通过/lian/bank/list接口获取)
	SettleIdcardNo        string `form:"settleIdcardNo"`        //结算人身份证号（非法人对私必填）
	SettleIdcardStartDate string `form:"settleIdcardStartDate"` //结算人身份证有效期起始日期（非法人对私必填） 格式：yyyy-MM-dd
	SettleIdcardEndDate   string `form:"settleIdcardEndDate"`   //结算人身份证有效期结束日期（非法人对私必填） 格式：yyyy-MM-dd
}

// MerchantTempBankAdd 添加商户结算信息
func MerchantTempBankAdd(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    MerchantTempBankAddForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	if len(form.Id) == 0 {
		appG.ResponseError("缺少参数id", nil)
		return
	}

	// 定义布局字符串，该字符串需要匹配dateTimeStr的格式
	layout := "2006-01-02"

	_, err := time.Parse(layout, form.SettleIdcardStartDate)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	_, err = time.Parse(layout, form.SettleIdcardEndDate)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	//结算卡正面照(图片id)（对公上传开户许可证）
	settleBankcardFrontPic, err := api.VerifyFileAndSave(c, "settleBankcardFrontPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	var fileList = make([]*channel.LianImgUploadParam, 0)
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, settleBankcardFrontPic), Remarks: "settleBankcardFrontPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleBankcardFrontPic"})
	var settleIdcardFrontPic, settleIdcardBackPic, settleAuthPic string
	if cast.ToInt(form.SettleAccountType) == 2 {
		//结算人身份证正面照(图片id)（非法人对私必填）
		settleIdcardFrontPic, err = api.VerifyFileAndSave(c, "settleIdcardFrontPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
		if err != nil {
			appG.ResponseError(err.Error(), nil)
			return
		}
		//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, settleIdcardFrontPic), Remarks: "settleIdcardFrontPic"})
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleIdcardFrontPic"})

		//结算人身份证反面照(图片id)（非法人对私必填）
		settleIdcardBackPic, err = api.VerifyFileAndSave(c, "settleIdcardBackPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
		if err != nil {
			appG.ResponseError(err.Error(), nil)
			return
		}
		//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, settleIdcardBackPic), Remarks: "settleIdcardBackPic"})
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleIdcardBackPic"})

		//结算授权书图片(图片id)（非法人对私必填）
		settleAuthPic, err = api.VerifyFileAndSave(c, "settleAuthPic", file.GetRandomFileName(), "temp/"+setting.GetConfig().App.MerchantPath+form.Id)
		if err != nil {
			appG.ResponseError(err.Error(), nil)
			return
		}
		//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("temp/merchantV1/"+form.Id, settleAuthPic), Remarks: "settleAuthPic"})
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleAuthPic"})

	}
	err = channel.LianImgUpload(fileList, cast.ToString(form.Id))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	merchantService := &merchantService.Merchant{
		Id:                     cast.ToInt(form.Id),
		SettleAccountType:      cast.ToInt(form.SettleAccountType),
		SettleName:             form.SettleName,
		SettleBankcardFrontPic: settleBankcardFrontPic,
		SettleBankcardNo:       form.SettleBankcardNo,
		SettleBankMobile:       form.SettleBankMobile,
		SettleSubbranchCode:    form.SettleSubbranchCode,
		SettleIdcardNo:         form.SettleIdcardNo,
		SettleIdcardStartDate:  form.SettleIdcardStartDate,
		SettleIdcardEndDate:    form.SettleIdcardEndDate,
		SettleIdcardFrontName:  settleIdcardFrontPic,
		SettleIdcardBackName:   settleIdcardBackPic,
		SettleAuthName:         settleAuthPic,
	}

	err = merchantService.MerchantTempSettleAdd()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("添加成功", nil)
}

type MerchantTempListParam struct {
	MerchantShopTypeId interface{} `json:"merchantShopTypeId"`
	MerchantTypeId     interface{} `json:"merchantTypeId"`
}

// MerchantTempList 商户列表
func MerchantTempList(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantTempListParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userId, exists := c.Get("userId")
	if !exists {
		appG.ResponseError("用户不存在", nil)
		return
	}

	merchantService := merchantService.Merchant{
		UserId:             cast.ToInt(userId),
		MerchantShopTypeId: cast.ToInt(param.MerchantShopTypeId),
		MerchantType:       cast.ToInt(param.MerchantTypeId),
	}
	result := merchantService.MerchantGetMerchantList()

	appG.ResponseSuccess("成功", result)
}

// LianMccList 获取经营范围列表
func LianMccList(c *gin.Context) {
	appG := app.Gin{C: c}

	merchantService := merchantService.Merchant{}
	result := merchantService.LianMccList()

	appG.ResponseSuccess("成功", result)
}

// LianCodeList 联动获取省市区列表
func LianCodeList(c *gin.Context) {
	appG := app.Gin{C: c}

	merchantService := merchantService.Merchant{}
	result := merchantService.LianCodeList()

	appG.ResponseSuccess("成功", result)
}

type LianBankListParam struct {
	Name string `json:"name"`
	City string `json:"city"`
}

// LianBankList 联动获取银行列表
func LianBankList(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    LianBankListParam
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{BankName: form.Name, BankCity: form.City}
	result := merchantService.LianBankList()

	appG.ResponseSuccess("成功", result)
}
